<template>
  <div>
    <el-row>
      <el-col :span="24" v-loading="showLoading">
        <div class="al-box-shadow-radius al-p-20px">
          <div>
            <span class="al-title-h3">发布我的作品</span>
            <el-button
                class="al-float-right"
                type="primary"
                round
                @click="sendRequest()">
                发布
            </el-button>

            <div class="al-box-size-10px al-float-right"></div>

            <el-button
                    class="al-float-right"
                    plain
                    round
                    @click="clearImageArray">
              清空
            </el-button>

          </div>

          <div class="al-m-top-20px">
            <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="sendData.content"
                maxlength="300"
                show-word-limit
                :autosize="{ minRows: 3}"
            >
            </el-input>
          </div>

          <div class="al-m-top-20px">
            <el-upload
                :action="uploadImg.url"
                list-type="picture-card"
                ref="upload"
                multiple
                name="file"
                :on-change="handleChange"
                :auto-upload="false">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                    <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                </span>
              </div>
            </el-upload>

<!--            <el-dialog :visible.sync="dialogVisible">-->
<!--              <img width="100%" :src="dialogImageUrl" alt="">-->
<!--            </el-dialog>-->

          </div>
        </div>


      </el-col>
    </el-row>

    <ALDialogTip :dialog-visible="dialogVisible"
                 @getSonData="getSonData"
                 tip-text="请先登录" />

  </div>

</template>

<script>
  import {request} from "@/util/network/request";
  import {GATEWAY_BASE_URL} from "../../../util/network/api/base/api-base";
  import {IMAGE_UPLOAD_RETURN_ID, IMAGE_UPLOAD_RETURN_URL} from "../../../util/network/api/image/api-image";
  import ALDialogTip from "../../../components/public/ALDialogTip";
  import {WORKS_ADD} from "../../../util/network/api/works/api-works";



  export default {
    name: "AddWorks",
    components: {ALDialogTip},
    data() {
      return {
        uploadImg: {
            //上传图片时需要用户id
            params: {
              uid: this.$store.state.storeUserInfo.id,
              isAlbum: 1
            },

            //上传图片请求的地址
            url: IMAGE_UPLOAD_RETURN_ID,
        },

        //要发送的数据
        sendData: {
          uid: this.$store.state.storeUserInfo.id,
          content: '',
          imgIds: ''

        },
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,

        //保存上传后返回的图片id
        imgId: '',
        disabled: false,
        //loading
        showLoading: false,
        imgIdArr:[],
        count: 0,

        //多图片上传用的几个data
        result:[],
        list:[],
        formDataList:[],
        localUploadUrl: 'http://localhost:9999/upload/image/return-id',

      }
    },

    mounted: function () {

    },

    methods: {
      //页面跳转
      goPage: function (path) {
        this.gotoPage(path);
      },

      //大小限制
      beforeAvatarUpload: function (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },


      //发表按钮的点击事件
      sendRequest() {
        let loginState = this.$store.state.storeIsLogin;
        console.log(loginState);
        if (!loginState){
          // this.$message.error("请先登录");
          this.dialogVisible = true;
        }else {
          // this.showLoading = true;
          //图片上传
          //this.submitUpload();
          this.uploadImage();
        }

      },

      //发送请求
      startRequest() {

        console.log("上传的数据：");
        console.log(this.sendData);

        request({
          method: 'post',
          url: WORKS_ADD,
          data: this.qsParam(this.sendData),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }

        }).then(res => {
          console.log(res);
          if (res.data.code == 1) {
            this.$message.success("发表成功");
            this.$emit("sonData", '');

            //清空图片数组
            this.clearImageArray();

            this.goPage('/works/all');
          } else {
            this.$message.error("发表失败");
            //清空图片数组
            this.clearImageArray();

          }
        }).catch(err => {
          console.log(err);
        })

      },

      //清空图片数组
      clearImageArray(){
        this.result = [];
        this.list = [];
        this.formDataList = [];
        this.sendData.content = '';
        this.sendData.imgIds = '';
        this.$refs.upload.clearFiles();
      },

      getSonData(data){
        console.log("getSonData");
        console.log(data);
        this.dialogVisible = data;
      },


      /**
       * 下面是图片上传的处理函数
       */
      //上传图片的处理函数
      uploadImage(){
        //将FormData组装成数组
        this.getFormDataList();

        //开始上传图片
        this.uploadRequest(this.formDataList, 0);

      },

      //将FormData组装成数组
      getFormDataList(){
        for (let file of this.list) {
          let formData = new FormData();
          formData.append("file", file);
          formData.append("uid", 1);
          formData.append("isAlbum", 1);
          this.formDataList.push(formData);
        }

        console.log(this.list);
      },

      //发起上传的请求
      uploadRequest(formDataList, index){
        request({
          url: IMAGE_UPLOAD_RETURN_ID,
          // url: this.localUploadUrl,
          method: 'post',
          data: formDataList[index],
          headers:{
            "content-type" : "multipart/form-data"
          }
        }).then(res => {
          console.log(res.data);
          this.result.push(res.data);
          console.log(this.result.join(";").toString());
          this.sendData.imgIds = this.result.join(";").toString();

          //递归上传下一张图片
          index++;
          if (index < formDataList.length){
            console.log("index: " + index);
            this.uploadRequest(formDataList, index);
          }

          //上传完最后一张之后的操作
          if (index == formDataList.length){
            this.$message.success("上传完成");

            //图片上传完成，开始发布作品
            this.startRequest();
          }
        }).catch(err => {
          console.log(err)
        })
      },

      handleBeforeUpload(file, fileList){
        // this.myFileList = fileList;
      },

      handleRemove(file, fileList) {
        console.log(file);
        fileList = [];
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      //文件改变时，获取到文件的file.raw
      handleChange(file, fileList){
        this.list.push(file.raw);
        console.log(this.list);
      }



    }


  }
</script>

<style scoped>

</style>
